import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

const Layout = () => import("../page/Layout.vue")
const Login = () => import("../page/Login.vue")
const Menu = () => import("../page/Menu.vue")
const Role = () => import("../page/Role.vue")
const User = () => import("../page/User.vue")
const Category = () => import("../page/Category.vue")
const Specs = () => import("../page/Specs.vue")
const Home = () => import("../page/Home.vue")
const Goods = () => import("../page/Goods.vue")
const routes = [
    {
      path: "/layout",
      component: Layout,
      meta: {
        isLogin: true,
        title: "首页"
      },
      children: [
        {
          path: "/goods",
          component: Goods,
          meta: {
            isLogin: true,
            title: "商品列表"
          }
        },
        {
          path: "/home",
          component: Home,
          meta: {
            isLogin: true,
            title: "管理中心"
          }
        },
        {
          path: "/specs",
          component: Specs,
          meta: {
            isLogin: true,
            title: "商品规格管理"
          }
        },
        {
          path: "/menu",
          component: Menu,
          meta: {
            isLogin: true,
            title: "菜单管理"
          }
        },
        {
          path: "/role",
          component: Role,
          meta: {
            isLogin: true,
            title: "角色管理"
          }
        },
        {
          path: "/user",
          component: User,
          meta: {
            isLogin: true,
            title: "管理员管理"
          },
        },
        {
          path: "/category",
          component: Category,
          meta: {
            isLogin: true,
            title: "商品分类管理"
          },
        }
      ]
    },
    {
      path: "/login",
      component: Login,
      meta: {
        isLogin: false,
        title: "登录"
      }
    },
    
]

const router = new VueRouter({
  routes
})


//编写路由守卫
// 没有token的就是没有登录的
// login 页面不需要登录
router.beforeEach(function(to,from,next){
  document.title = to.meta.title
  const to_path = to.path
  
  const no_login = ["/login","/index","/list","/home"] //定义一个白名单
  // if(to.meta.isLogin) //元信息方式
  if(no_login.indexOf(to_path) === -1){ //检查是否再白名单当中
    //不满足白名单，校验token
    const token = JSON.parse(localStorage.getItem("loginData")||'{}').token
    if(!token){
      next("/login")
    }
  }
  next()
})
//校验页面的访问权限
router.beforeEach(function(to,from,next){
  const localsotrage = JSON.parse(localStorage.getItem("loginData")||'{}')
  var menu_list = localsotrage.menus_url 
  if(menu_list){
    menu_list.push("/home") //公共可以访问的页面
    menu_list.push("/layout")
    menu_list.push("/login")
    var index = menu_list.indexOf(to.path)
    if(index === -1){
      return next("/home")
    }
  }
  return next()
})

export default router
